﻿// //////////////////// upload file ///////////////////////////////

var img_filename='';

// 根据用户ID将用户ID转换成相对应的ASCII编码
function userIdToASCII() {
	var uid = UserSohuID;
	uid = $A(uid.toString());
	var uid_ascii = 0;
	for(var i=0;i<uid.length;i++) {
		uid_ascii += uid[i].charCodeAt();
	}
	return uid_ascii;
}

// 发送邮件时创建一个层，盖住整个页面，防止用户去做其他的操作，当从服务器端返回结果的时候再清除这个层
function createDiv4Sending() {
	/*
	var div = '<div id="div4sending" style="background:#CCCCCC;position:absolute;top:0px;left:0px;width:100%;height:100%;z-index:999;"><span> &nbsp; </span></div>';
	new Insertion.Bottom(document.body, div);
	Element.setStyle($('div4sending'), {filter:'Alpha(opacity=30)',opacity:0.3,mozOpacity:0.3,khtmlOpacity:0.3});
	*/
	Tips.show("邮件正在发送，请稍候...");
}

function createDiv4Saving() {
	/*
	var div = '<div id="div4sending" style="background:#CCCCCC;position:absolute;top:0px;left:0px;width:100%;height:100%;z-index:999;"><span> &nbsp; </span></div>';
	new Insertion.Bottom(document.body, div);
	Element.setStyle($('div4sending'), {filter:'Alpha(opacity=30)',opacity:0.3,mozOpacity:0.3,khtmlOpacity:0.3});
	*/
	Tips.show("邮件正在保存中，请稍候...");
}

function createShadowDiv() {
	/*
	var h = $('composeMail').getHeight() > 0 ? $('composeMail').getHeight()+'px' : '100%';
	var div = '<div id="div4sending" style="background:#CCCCCC;position:absolute;top:80px;left:'+ staticValue.leftWidth +'px;width:100%;height:'+ h +';z-index:999;"><span> &nbsp; </span></div>';
	Element.insert($('sohuMailMain'), {bottom: div});
	Element.setStyle($('div4sending'), {filter:'Alpha(opacity=30)',opacity:0.3,mozOpacity:0.3,khtmlOpacity:0.3});
	*/
}

function removeDiv4Sending() {
	/*
	try {
		$("div4sending").remove();
		MessagePanel.hide();
	} catch (e) {}
	*/
	try {
		Tips.hide();
	} catch(e) {}
}


// 缓存当前正在使用的上传附件对象
var currentUploadObject = null;

// 附件串行上传机制封装
var MailUploadFile = Class.create();
MailUploadFile.prototype = {
    initialize: function(form_id, info_id, max_size){
		this.init();
		// form表单添加到DOM元素的ID
		this.insertID = 'uploadArea';
		// 上传提示信息的DOM元素ID
		this.infoID = 'upload_info';
		// 允许附件上传的最大值
		this.FILE_MAX_SIZE = G.maxAttachmentSize;//1024*1024*10;
		// 上传附件的URL
		this.uploadUrl = './mail/att';
		// 上传附件时post文件的name
		this.postName = 'upload_file';
		if(form_id && typeof(form_id) == "string") {
			this.insertID = form_id;
		}
		if(info_id && typeof(info_id) == "string") {
			this.infoID = info_id;
		}
		if(max_size && typeof(max_size) == "number") {
			this.FILE_MAX_SIZE = max_size;
		}
    },
    init: function(){
		// 当前页面的domain
		// this.uploadDomain = localDomain;
		this.uploadDomain = isDomain ? localDomain : undefined;
        // 是否有附件正在上传
        this.uploading = false;
		// 记录准备上传，正在上传，上传成功的文件对象(检测是否有重复的文件上传通过这个数组)
		this.FILES_INFOS = [];
		// 记录准备上传，正在上传的附件对象(上传成功的将从队列中删除，未上传的在队列中排队等候)
		this.FILES_UPLOADING = [];
		// 接收附件返回值的Iframe
		// this._uploadIframe = '<iframe name="file_upload_ifr" id="file_upload_ifr" src="./mail/att" style="border:0px;width:100px;height:100px;" frameborder=0></iframe>';
		var _d = this.uploadDomain ? 'document.domain=\''+ this.uploadDomain +'\';' : '';
		this.uploadIframe = '<iframe name="file_upload_ifr" id="file_upload_ifr" src="javascript:document.open(\'text\/html\',\'replace\');'+ _d +'document.write(\'<head><meta http-equiv=Content-Type content=text/html;charset=utf-8 /></head><body><div><span> &nbsp; </span></div></body>\');document.close();" style="border:0px;width:0px;height:0px;position:absolute;left:-6000px;top:-6000px;" frameborder=0></iframe>';
		
		this.uploadImageIframe = '<iframe name="file_upload_image" id="file_upload_image" src="javascript:document.open(\'text\/html\',\'replace\');'+ _d +'document.write(\'<head><meta http-equiv=Content-Type content=text/html;charset=utf-8 /></head><body><div><span> &nbsp; </span></div></body>\');document.close();" style="border:0px;width:0px;height:0px;position:absolute;left:-6000px;top:-6000px;" frameborder=0></iframe>';
		
		// 随机ID
		this.randomID = Math.floor(Math.random()*10000*10000);
		
		// 初始附件大小
		this.INIT_FILE_SIZE = 0;
		//头像，签名大小
		this.IMAGE_SIZE=50*1024;
		// 记录当前正在上传的附件ID，Name
		this.currentFile = {fid: "", filename: ""};
		// 上传进度ID
		this.PROGRESS_ID = this.createRandom();
		// 上传进度的timer
		this.Progressing = null;
		// 获取上传进度条信息
		this.progress_bar = false;
		// 初始化上传附件的iframe
		if(!$('file_upload_ifr')) this.createIframe();
		// 初始化上传图片的iframe
		if(!$('file_upload_image')) this.createImageIframe();
		
		//判断头像上传 
		this.avatarObj = null;
		this.signObj = null;
    },
	setCurrentFile: function(fid, filename) {
		if(arguments.length == 0) {
			this.currentFile.fid = '';
			this.currentFile.filename = '';
			return false;
		}
		this.currentFile.fid = fid;
		this.currentFile.filename = filename;
	},
	// 附件上传事件，根据file input中的onchange事件触发事件上传
	// fobj: Object, 上传附件的form表单的DOM对象
	startUpload: function(fobj, fid) {
		for(var key in mailConference._upload) {
			if(mailConference._upload[key] != currentUploadObject && mailConference._upload[key].uploading) {
				_dialog.alert({info: '附件正在上传，请稍后'});
				return false;
			}
		}
		currentUploadObject = this;
		var fname = fobj[this.postName].value;
		if(fname.strip() == '') return;
		var uploadInput = '<input id="'+ this.postName +'" name="'+ this.postName +'" type="file" value="" style="cursor:pointer;" size=1 />';
		if (!fname.blank()) {
			fname = fname.substring(fname.lastIndexOf('\\') + 1, fname.length);
		}
		try {
			var e = fname.substring(fname.lastIndexOf('.') + 1, fname.length);
			var self = this;
			if (!this.filterFileName(e)) {
				setTimeout(function() {
					self.clearEvent(fobj);
					fobj.innerHTML = uploadInput;
					var _self = self;
					fobj.getElementsByTagName('input')[0].onchange = function() {
						_self.startUpload(this.parentNode, fid);
					};
				}, 10);
				return;
			}
			if (this.FILES_INFOS.length > 0) {
				for (var i=0; i < this.FILES_INFOS.length; i++) {
					if (this.FILES_INFOS[i].filename == fname) {
						setTimeout(function() {
							fobj.innerHTML = uploadInput;
							var _self = self;
							fobj.getElementsByTagName('input')[0].onchange = function() {
								_self.startUpload(this.parentNode, fid);
							};
						}, 10);
						_dialog.alert({info: '这个文件已经存在了'});
						return;
					}
				}
			}
		}catch(e) {}
		var faction = fobj.getAttribute('action').split('=');
		if (faction[1] && faction[1] != null) {
			this.PROGRESS_ID = parseInt(faction[1]);
		}
		var fileInfo = {
			fid: fid,
			filename: fname,
			success: false,
			size: 0,
			type: '',
			id: '',
			progress_id: this.PROGRESS_ID
		};
		this.FILES_INFOS.push(fileInfo);
		this.FILES_UPLOADING.push(fileInfo);
		
		this.createForm(this.PROGRESS_ID);
		this.createInfo(fname, fid);
		if (this.uploading == false) {
			this.uploading = true;
			var that = this;
			setTimeout(function() {
				fobj.submit();
				that.setCurrentFile(fid, fname);
				var self = that;
				setTimeout(function() {
					self.progressUpload(that.PROGRESS_ID, true);
				}, 200);
			}, 400);
		}
	},
	
	// 过滤上传文件名称
	filterFileName: function(name) {
		var filterName = ["cmd", "cpl", "exe", "hta", "pif", "scr", "vbs", "vsd"];
		if (filterName.include(name.toLowerCase())) {
			_dialog.alert({info: '附件不能是 "cmd", "cpl", "exe", "hta", "pif", "scr", "vbs", "vsd" 这些格式的'});
			return false;
		}
		return true;
	},
	
	// 头像，签名上传事件，根据file input中的onchange事件触发事件上传
	// fobj: Object, 上传附件的form表单的DOM对象
	imageUpload: function(fobj) {
		var fname = fobj.upload_image.value;
		var uploadInput = '<input type="file" name="upload_image" id="upload_image" />&nbsp;&nbsp;<input name="button" type="button"  class="yes" value="上 传" onclick="mailUploadFile.imageUpload(this.parentNode);"/>';
		var filterName = ["jpg", "gif"];
		if (!fname.blank()) {
			fname = fname.substring(fname.lastIndexOf('\\') + 1, fname.length);
		}
		try {
			var e = fname.substring(fname.lastIndexOf('.') + 1, fname.length);
			if (!filterName.include(e.toLowerCase())) {
				setTimeout(function() {
					fobj.innerHTML = uploadInput;
				}, 10);
				_dialog.alert({info: '请上传jpg、gif格式的图片文件！'});
				$('upload_image').disabled=false;
				$('uploadImage').disabled=false;	
				$('upload_image').value="";
				return;
			}		
		}catch(e) {}
		if (this.uploading == false) {
			this.uploading = true;
			var that = this;
			setTimeout(function() {
				fobj.submit();
				that.setCurrentFile(fname);
				$('upload_image').disabled=true;
				$('uploadImage').disabled=true;	
			}, 400);

		}
	},
	
	// 图片上传成功，从上传附件的返回iframe页面中调用成功函数
	// res: Object, JSON数据，里面返回了数据上传的成功与否
	imageUploadTwo: function(res) {
		var ret = res.evalJSON();
		img_filename=ret.filename;
		this.uploading = false;
		if (ret.is_success) {
			if(ret.type=="0"){
				this.createEndImg(ret.filename);
			}else{
				this.createEndAvatar(ret.filename);
			}
			
			try {
				// 上传成功之后重置Iframe
				this.createImageIframe();
				this.setCurrentFile("");
			} 
			catch (e) {}
		} else {
				_dialog.alert({info: ret.message});
				$('upload_image').disabled=false;
				$('uploadImage').disabled=false;
				$('upload_image').value="";
		}
	},
	
	// 附件上传成功，从上传附件的返回iframe页面中调用成功函数
	// res: Object, JSON数据，里面返回了数据上传的成功与否
	endUpload: function(res) {
		var ret = res.evalJSON();
		this.uploading = false;
		if (ret.is_success) {
			this.INIT_FILE_SIZE += ret.size;
			ret.filename = ret.filename.unescapeHTML();
			this.createEnd(ret.filename, ret.size, ret.id);
			var fid = null;
			var next = null;
			var index = null;
			try {
				for (var i = 0; i < this.FILES_UPLOADING.length; i++) {
					if (this.FILES_UPLOADING[i].filename == ret.filename) {
						index = i;
						fid = this.FILES_UPLOADING[i].fid;
						this.FILES_UPLOADING[i].success = ret.is_success;
						this.FILES_UPLOADING[i].size = ret.size;
						this.FILES_UPLOADING[i].type = ret.type;
						this.FILES_UPLOADING[i].id = ret.id;
						if ((i+1) <= this.FILES_UPLOADING.length) {
							next = this.FILES_UPLOADING[i+1];
						}
					}
				}
				
				// 上传成功之后删除上传的Form表单
				Element.remove($('file_upload_form_' + fid));
				// 上传成功之后重置Iframe
				this.createIframe();
				// 如果上传附件的累计大小超出总大小
				if (this.INIT_FILE_SIZE > this.FILE_MAX_SIZE) {
					this.deleteUpload(this.FILES_UPLOADING[index].fid, this.FILES_UPLOADING[index].filename);
					var clearF = this.FILES_UPLOADING.splice(index+1);
					if(clearF.length > 0) {
						for(var ii=0; ii<clearF.length; ii++) {
							this.stopUpload(clearF[ii].filename, clearF[ii].fid);
						}
					}
					_dialog.alert({info: '您上传附件的总大小超出了规定大小！'});
					return;
				}
				if (typeof(index) == "number") {
					this.FILES_UPLOADING.splice(index, 1);
				}
				this.setCurrentFile("", "");
				// 如果用户在发信界面调用的附件上传，并且发信主题为空
				try {
					var self = this;
					var _tfn = setTimeout(function() {
						clearTimeout(_tfn);
						_tfn = null;
						if(self == mailUploadFile) {
							writemail.filename2Subject(ret.filename);
						}
					}, 100);
				} catch(e) { }
				// 上传成功之后进行队列中的下一个文件上传
				if (next && next != null && this.uploading == false) {
					if (!next.success) {
						this.uploading = true;
						var that = this;
						setTimeout(function() {
							// this.startUpload($('file_upload_form_' + next.id), next.id);
							$('file_upload_form_' + next.fid).submit();
							that.setCurrentFile(next.fid, next.filename);
							var self = that;
							setTimeout(function() {
								self.progressUpload(next.progress_id, true);
							}, 200);
						}, 600);
					}
				}
			} 
			catch (e) {}
		} else {
			this.stopUpload(this.currentFile.filename, this.currentFile.fid);
			if (ret.message == "Upload file exceed size limit!") {
				_dialog.alert({info: '附件大小超出，请返回写信页编辑'});
			} else {
				_dialog.alert({info: ret.message});
			}
		}
	},
	// 停止正在上传的附件，重新创建接受上传附件返回结果的iframe
	stopUpload: function(filename, fid) {
		var next = null;
		var index = null;
		try {
			for (var i = 0; i < this.FILES_UPLOADING.length; i++) {
				if (this.FILES_UPLOADING[i].fid == fid) {
					index = i;
					if ((i + 1) <= this.FILES_UPLOADING.length) {
						next = this.FILES_UPLOADING[i + 1];
					}
				}
			}
		} catch(e) {}
		try {
			var indexj = null;
			for (var j = 0,len2 = this.FILES_INFOS.length; j < len2; j++) {
				if (this.FILES_INFOS[j].filename == filename) {
					indexj = j;
				}
			}
		} catch(e) {}
		try {
			if (typeof(index) == "number") {
				this.FILES_UPLOADING.splice(index, 1);
			}
		} catch(e) {}
		try {
			if (typeof(indexj) == "number") {
				this.FILES_INFOS.splice(indexj, 1);
			}
		} catch(e) {}
		try {
			var _fuf = $('file_upload_form_'+fid);
			if(_fuf) {
				this.clearEvent(_fuf);
				Element.remove(_fuf);
			}
		} catch(e) {}
		try {
			var _fui = $('file_upload_info_'+filename);
			if (_fui) {
				this.clearEvent(_fui);
				Element.remove(_fui);
			}
			if(this.FILES_INFOS.length == 0) {
				$(this.infoID).hide();
			}
		} catch(e) {}
		// 判断停止的是否是当前正在上传的附件
		try {
			if (filename != this.currentFile.filename && fid != this.currentFile.fid) {
				return;
			}
		} catch(e) {}
		this.uploading = false;
		// 为下一个文件的上传做准备
		try {
			this.createIframe();
			this.setCurrentFile("", "");
			// 上传成功之后进行队列中的下一个文件上传
			var that = this;
			if (next && next != null && this.uploading == false) {
				if (!next.success) {
					this.uploading = true;
					setTimeout(function(){
						$('file_upload_form_' + next.fid).submit();
						that.setCurrentFile(next.fid, next.filename);
						var self = that;
						setTimeout(function(){
							self.progressUpload(next.progress_id, true);
						}, 200);
					}, 600);
				}
			}
		} catch(e) {}
	},
	// 删除已经上传成功的附件
	// file_id: number，上传成功附件的ＩＤ
	deleteUpload: function(file_id, file_name) {
		var fid = null;
		var indexj = null;
		for (var j=0; j < this.FILES_INFOS.length; j++) {
			if (this.FILES_INFOS[j].filename == file_name) {
				indexj = j;
				fid = this.FILES_INFOS[j].fid;
			}
		}
		if (typeof(indexj) == "number") {
			this.INIT_FILE_SIZE -= this.FILES_INFOS[indexj].size;
			this.FILES_INFOS.splice(indexj, 1);
		}
		try {
			var _fui = $('file_upload_info_'+file_name);
			if(_fui) {
				this.clearEvent(_fui);
				Element.remove(_fui);
			}
			if(this.FILES_INFOS.length == 0) {
				$(this.infoID).hide();
			}
		} catch(e) {}
		try {
			var params = {
				id : file_id
			};
			mail_del_att(params);
		} catch(e) {}
		// this.setCurrentFile("", "");
	},
	// 上传附件的时候出现Error(多数情况下可能是apache端返回的proxy error)
	errorUpload: function() {
		
	},
	// 创建正在上传的进度信息
	progressUpload: function(progress_id, initp) {
		if(initp) {
			clearTimeout(this.Progressing);
			this.Progressing = null;
		}
		var params = {
			'X-Progress-ID': progress_id
		};
		var that = this;
		if (this.progress_bar) {
			setTimeout(function() {
				that.progressUpload(progress_id, initp);
			}, 1000);
			return;
		}
		_defun('./mail/att/progress', 'get', params, this.progressUploadSuccessCallback.bind(this, progress_id), this.progressUploadFailureCallback.bind(this, progress_id));
		this.progress_bar = true;
	},
	progressUploadSuccessCallback: function(progress_id, ret) {
		this.progress_bar = false;
		ret = eval(ret);
		var _upb = $('upload_progress_' + progress_id);
		if(ret.state == "starting") {
			this.startStatusLoading(_upb);
		} else if(ret.state == "uploading") {
			this.endStatusLoading();
			if(ret.size > this.FILE_MAX_SIZE) {
				var ename = this.currentFile.filename;
				this.stopUpload(this.currentFile.filename, this.currentFile.fid);
				_dialog.alert({info: ename + " 附件大小超出，请返回写信页编辑"});
				return;
			}
			if(ret.received != -1 && ret.size != -1) {
				var w = (ret.received*100)/ret.size;
				if (w > parseFloat(_upb.style.width)) {
					// Element.setStyle(_upb, {width: w+"%"});
					_upb.style.width = w+'%';
					this.startStatusLoading(_upb);
					/*
					var self = this;
					this.startStatusLoaded(_upb, {
						start: parseFloat(_upb.style.width),
						end: w,
						callback: function() {
							self.startStatusLoading(_upb);
						}
					});
					*/
				}
			}
		} else if(ret.state == "error") {
			this.endStatusLoading();
			var ename = this.currentFile.filename;
			this.stopUpload(this.currentFile.filename, this.currentFile.fid);
			if(ret.status == '413') {
				_dialog.alert({info: ename + ' 附件大小超出，请返回写信页编辑'});
			} else if(ret.status == '408') {
				_dialog.alert({info: '附件上传超时，可能由于您的网络过慢，请检查您的网络状况'});
			} else {
				_dialog.alert({info: '附件上传出错，请重新尝试'});
			}
			return;
		} else if(ret.state == "done") {
			this.endStatusLoading();
			return;
		}
		var that = this;
		if (this.uploading) {
			this.Progressing = setTimeout(function() {
				that.progressUpload(progress_id);
			}, 3000);
		}
	},
	// 上传附件时，进度条时间间隔的动画效果
	startStatusLoading: function(el) {
		var _default = {
			second: 1,
			distance: 2
		};
		var s1 = parseFloat(el.style.width);
		if(s1 > 99) return false;
		var _index = 0;
		var self = this;
		this.statusLoading = setInterval(function() {
			_index++;
			var p = s1 + (0.2*_index);
			if(p > 99) {
				self.endStatusLoading();
				return false;
			}
			el.style.width = s1 + (0.2*_index) + '%';
		}, 100);
	},
	endStatusLoading: function() {
		if(this.statusLoading) {
			clearInterval(this.statusLoading);
			this.statusLoading = null;
		}
		try {
			if(this._ff_ifr) {
				this._ff_ifr.remove();
				this._ff_ifr = null;
			}
			this._ff_ifr = document.createElement('iframe');
			document.body.appendChild(this._ff_ifr);
		} catch(e) {}
	},
	// 真实上传值的动画
	startStatusLoaded: function(el, option) {
		/*
		option = {
			start: 0,
			end: 1,
			callback: function() {
			}
		};
		*/
		var s1 = parseFloat(el.style.width);
		var _t = (option.end - option.start)/10;
		var _index = 0;
		var self = this;
		this.statusLoaded = setInterval(function() {
			_index++;
			if(_index > 10) {
				self.endStatusLoaded();
				option.callback();
			}
			el.style.width = s1 + (_t*_index) + '%';
		}, 100);
	},
	endStatusLoaded: function() {
		if(this.statusLoaded) {
			clearInterval(this.statusLoaded);
			this.statusLoaded = null;
		}
	},
	progressUploadFailureCallback: function(progress_id) {
		this.progress_bar = false;
		var that = this;
		if (this.uploading) {
			this.Progressing = setTimeout(function() {
				that.progressUpload(progress_id);
			}, 3000);
		}
	},
	// 创建上传附件的form表单
	createForm: function(progress_id) {
		var progress_id = this.createRandom();
			var uploadForm = '<form style="position:absolute;left:0px;top:0px;z-index:1;width:60px;opacity:0;filter:Alpha(opacity=0);" name="file_upload_form_'+ progress_id +'" id="file_upload_form_'+ progress_id +'" action="'+ this.uploadUrl +'?X-Progress-ID='+ progress_id +'" method="post" target="file_upload_ifr" enctype="multipart/form-data">'
						 +'<input id="'+ this.postName +'" name="'+ this.postName +'" type="file" value="" style="cursor:pointer;width:0px;" size=1 />'
						 +'</form>';
		try {
			var _fuf = $('file_upload_form_'+progress_id);
			if (_fuf) {
				this.clearEvent(_fuf);
				Element.remove(_fuf);
			}
			Element.insert($(this.insertID), {bottom: uploadForm});
			// $(this.insertID).innerHTML = uploadForm;
			var self = this;
			$('file_upload_form_'+progress_id).getElementsByTagName('input')[0].onchange = function() {
				self.startUpload(this.parentNode, progress_id);
			};
		} catch(e) {}
	},
	// 创建接受返回值的iframe
	createIframe: function() {
        try {
			var _fui = $('file_upload_ifr');
        	if (_fui && typeof(frames['file_upload_ifr']) == "object") {
        		try {
					var _fw = frames['file_upload_ifr'];
        			// for IE
					// frames['file_upload_ifr'].document.execCommand('Stop');
					if(Prototype.Browser.IE) 
						_fw.document.execCommand('Stop', false, '');
					else 
						_fw.window.stop();
        		} catch(e) {}
				try {
					_fui.remove();
					_fui = null;
				} catch(e) {}
        	}
			$(document.body).insert({bottom:this.uploadIframe});
            // setTimeout(function() {
            Element.insert(document.body, {bottom: this.uploadIframe});
            // }, 100);
        } catch (e) {}
        
	},
	
	// 创建接受返回值的iframe
	createImageIframe: function() {
        try {
        	if ($('file_upload_image') && typeof(frames['file_upload_image']) == "object") {
        		try {
        			// for IE
        			window.frames['file_upload_image'].document.execCommand('Stop');
        		} catch(e) {}
        		Element.remove($('file_upload_image'));
        	}
           	// var that = this;
            // setTimeout(function() {
            Element.insert(document.body, {bottom: this.uploadImageIframe});
            // }, 100);
        } catch (e) {}
        
	},
	
	// 创建正在上传附件的提示信息区域
	createInfo: function(filename, id) {
		var fileInfo = '<dl id="file_upload_info_'+ filename +'" style="white-space:nowrap;"><dd><table collspacing=0 collpadding=0 border=0><tbody><tr><td>'+ filename +'</td><td><div style="width:300px;height:8px;font-size:0pt;border:1px solid #F5AA69;margin:8px auto;"><div id="upload_progress_'+ this.PROGRESS_ID +'" style="background:#FFBD4B url(\''+ MailConst.ALL +'/pic_rate.gif\') repeat-x;height:100%;width:0%;"></div></div></td><td><a hidefocus="true" href="javascript:;" onclick="return false;" id="file_upload_delete_'+ id +'"> 取消 </a>, </td></tr></tbody></table></dd></dl>';
		var _fui = $('file_upload_info_'+filename);
		if (_fui) {
			this.clearEvent(_fui);
			Element.remove(_fui);
		}
		Element.insert($(this.infoID), {bottom: fileInfo});
		try {
			var _a = $('file_upload_delete_' + id);
			if(_a) {
				_a.observe('click', function(event) {
					self.stopUpload(filename, id);
				}.bind(this));
			}
			/*
			if(_a) {
				var self = this;
				_a.onclick = function(event) {
					self.stopUpload(filename, id);
					return false;
				};
			}
			*/
		} catch(e) {}
		if(this.FILES_INFOS.length > 0) {
			$(this.infoID).show();
		}
	},
	// 创建上传成功的附件信息
	createEnd: function(filename, size, f_id) {
		var fid = null;
		for (var i=0; i < this.FILES_UPLOADING.length; i++) {
			if(this.FILES_UPLOADING[i].filename == filename) {
				fid = this.FILES_UPLOADING[i].fid;
			}
		}
		try {
			var _fui = $('file_upload_info_'+filename);
			this.clearEvent(_fui);
			_fui.innerHTML = '<dd>'+ filename +' <b id="file_upload_size_'+ fid +'"> ('+ strfsize(size) +') <img src="'+ MailConst.ALL +'/duigou.jpg" /><a hidefocus="true" href="javascript:;" onclick="return false;" id="file_upload_delete_'+ fid +'"> 删除 </a>, </b></dd>';
			try {
				var _a = $('file_upload_delete_' + fid);
				if(_a) {
					_a.observe('click', function(event) {
						this.deleteUpload(f_id, filename);
					}.bind(this));
				}
				/*
				if(_a) {
					var self = this;
					_a.onclick = function(event) {
						self.deleteUpload(f_id, filename);
						return false;
					};
				}
				*/
			} catch(e) {}
		} catch(e) {}
	},
	
	// 创建上传成功的图片信息
	createEndImg: function(filename) {
		if(this.signObj == null) {
			this.signObj = new Cropper.ImgWithPreview();
		}
		$('uploadImage').disabled=false;
		$('upload_image').value="";
		$('upload_image').disabled=false;
		$('bgDiv').innerHTML = '<img id="signImage" style="border: 1px none rgb(204, 204, 204); z-index: 1; display: block;"/>';
		Element.show($('imgDiv'));
		$('signImage').setAttribute('src', SIGN_ROOT+'/'+filename+'?'+Math.random());
		this.signObj.init('signImage', {
				minWidth: 148,
				minHeight: 106,
				ratioDim: {x: 148, y: 106},
				displayOnInit: true,
				previewWrap: 'previewArea',
				onEndCrop: function() {
					try {
						var p = arguments;
						if (p.length < 2) return false;
						position_sign.clear();
						position_sign[0] = p[0].x1;
						position_sign[1] = p[0].y1;
						position_sign[2] = p[1].width;
						position_sign[3] = p[1].height;
					} catch(e) {}
				}
			}
		);
	},
	
	// 创建上传成功的图片信息
	createEndAvatar: function(filename) {
		if(this.avatarObj == null) {
			this.avatarObj = new Cropper.ImgWithPreview();
		}
		$('uploadImage').disabled=false;
		$('upload_image').disabled=false;
		$('upload_image').value="";
		$('bgDiv1').innerHTML = '<img id="avatarImage" style="border: 1px none rgb(204, 204, 204); z-index: 1; display: block;"/>';
		Element.show($('imgDiv1'));
		$('avatarImage').setAttribute('src', SIGN_ROOT+'/'+filename+'?'+Math.random());
		this.avatarObj.init('avatarImage', { 
				minWidth: 108, 
				minHeight: 85,
				ratioDim: { x: 108, y: 85 },
				displayOnInit: true,
				previewWrap: 'previewArea1',
				onEndCrop: function() {
					try {
						var p = arguments;
						if (p.length < 2) return false;
						position_avatar.clear();
						position_avatar[0] = p[0].x1;
						position_avatar[1] = p[0].y1;
						position_avatar[2] = p[1].width;
						position_avatar[3] = p[1].height;
					} catch(e) {}
				}
			}
		);
	},
	
	// 创建初始化已经创建成功的附件信息（从已带附件的草稿箱进入写信状态，或者已带附件的转发信件）
	createInitInfo: function(file_obj) {
		if (file_obj.length > 0) {
			$(this.infoID).show();
			file_obj.each(function(item) {
				this.INIT_FILE_SIZE += item.size;
				var fileInfo = '<dl id="file_upload_info_'+ item.filename +'"><dd>'+ item.filename +' <b id="file_upload_size_'+ item.id +'"> ('+ strfsize(item.size) +') <a hidefocus="true" href="javascript:;" onclick="return false;" id="file_upload_delete_'+ item.id +'"> 删除 </a>, </b></dd></dl>';
				var _fui = $('file_upload_info_' + item.filename);
				if (_fui) {
					this.clearEvent(_fui);
					Element.remove(_fui);
				}
				Element.insert($(this.infoID), {bottom: fileInfo});
				try {
					var _a = $('file_upload_delete_' + item.id);
					if(_a) {
						var self = this;
						_a.onclick = function(event) {
							self.deleteUpload(item.id, item.filename);
						};
					}
				} catch(e) {}
				var fileInfo = {
					fid: '',
					filename: item.filename,
					success: true,
					size: item.size,
					type: item.type,
					id: item.id,
					progress_id: 0
				};
				this.FILES_INFOS.push(fileInfo);
			}.bind(this));
		}
	},
	// 清除事件
	clearEvent: function(id) {
		var _event = ['onclick', 'onchange'];
		$A($(id).getElementsByTagName('*')).each(function(item) {
			_event.each(function(_item) {
				if(item[_item]) item[_item] = null;
			});
		});
	},
	destroy: function() {
		try {
			this.clearEvent(this.insertID);
		} catch(e) { }
		try {
			this.clearEvent(this.infoID);
		} catch(e) { }
	},
	// 创建随机数
	createRandom: function() {
		return Math.floor(Math.random()*10000*10000);
	}
};
var mailUploadFile = new MailUploadFile('upload_iframe_content', 'uploadInfoDIV');

function uploadSuccess(info) {
	// mailUploadFile.endUpload(info);
	try {
		currentUploadObject['endUpload'](info);
	} catch(e) {}
}

function imageUploadSuccess(info){
	mailUploadFile.imageUploadTwo(info);
}



/********************************** 创建photo的上传 ***********************************/
var mailUploadPhoto = new MailUploadFile('upload_photo', 'upload_photo_info', 1024*1024*100);
mailUploadPhoto.uploadUrl = '/postcard/uploadimg';
mailUploadPhoto.postName = 'filename';
mailUploadPhoto.isUser = false;
mailUploadPhoto.progressUpload = function() { };
mailUploadPhoto.filterFileName = function(name) {
	var filterName = ['jpg', 'jpeg', 'gif', 'bmp'];
	if(!filterName.include(name.toLowerCase())) {
		_dialog.alert({info: '只能上传 jpg, jpeg, gif, bmp 格式的图片'});
		return false;
	}
	return true;
};

mailUploadPhoto.createInfo = function(filename, id) {
	return false;
	var photoInfo = '<div id="photo_upload_info_'+ id +'" style="font-size: 8px; width: 80px; height: 60px; border: 0px; padding: 5px; float: left;" onmouseover="" onmouseout=""><img src="'+ MailConst.ALL +'/loading_2.gif" title="'+ filename +'" style="margin: 14px 24px;width: 32px; height: 32px; border: 0px;" /></div>'
	if ($('photo_upload_info_' + id)) {
		Element.remove($('photo_upload_info_' + id));
	}
	Element.insert($(this.infoID), {top: photoInfo});
	if(this.FILES_INFOS.length > 0) {
		Element.show($(this.infoID).parentNode.parentNode);
		var _inner_w = Element.getWidth($('photo_upload_info_' + id)) * $A($('upload_photo_info').getElementsByTagName('div')).length + 2;
		Element.setStyle($(this.infoID), {width: _inner_w + 'px'});
		if(_inner_w > Element.getWidth($(this.infoID).parentNode)) {
			$('upload_photo_prev').style.visibility = 'visible';
			$('upload_photo_next').style.visibility = 'visible';
		}
	}
	$('photo_upload_info_'+ id).onmouseover = function() {
		if(this.getAttribute('focus') == 'true') return;
		with(this.style) {
			backgroundColor = '#EEEEEE';
			border          = '1px solid #CCCCCC';
			padding         = '4px';
			cursor          = 'pointer';
		};
	};
	$('photo_upload_info_'+ id).onmouseout = function() {
		if(this.getAttribute('focus') == 'true') return;
		with(this.style) {
			backgroundColor = 'transparent';
			border          = '0px';
			padding         = '5px';
			cursor          = 'text';
		};
	};
};

mailUploadPhoto.endUpload = function(ret) {
	var ret = ret.evalJSON();
	this.uploading = false;
	if (typeof ret.success == 'number') {
		this.createEnd(ret);
		var fid = null;
		var next = null;
		var index = null;
		try {
			for (var i = 0; i < this.FILES_UPLOADING.length; i++) {
				if (this.FILES_UPLOADING[i].fid == ret.progressID) {
					index = i;
					fid = this.FILES_UPLOADING[i].fid;
					this.FILES_UPLOADING[i].success = ret.success;
					if ((i+1) <= this.FILES_UPLOADING.length) {
						next = this.FILES_UPLOADING[i+1];
					}
				}
			}
			// 上传成功之后删除上传的Form表单
			Element.remove($('file_upload_form_' + fid));
			// 上传成功之后重置Iframe
			this.createIframe();
			// 如果上传附件的累计大小超出总大小
			if (typeof(index) == "number") {
				this.FILES_UPLOADING.splice(index, 1);
			}
			this.setCurrentFile("", "");
			// 上传成功之后进行队列中的下一个文件上传
			if (next && next != null && this.uploading == false) {
				if (next.success == false) {
					this.uploading = true;
					var that = this;
					setTimeout(function() {
						$('file_upload_form_' + next.fid).submit();
						that.setCurrentFile(next.fid, next.filename);
						var self = that;
						setTimeout(function() {
							self.progressUpload(next.progress_id, true);
						}, 200);
					}, 600);
				}
			} else {
				if (ret.success == 1) {
					changePostcardPhoto(this.uploadUrl + '?uname=' + ret.imgurl, ret, true, $('photo_upload_info_' + ret.progressID));
				}
			}
		} catch (e) {}
	}
};

mailUploadPhoto.createEnd = function(ret) {
	var errImg = function(id) {
		/*
		Element.remove($('photo_upload_info_' + id));
		if($A($(this.infoID).getElementsByTagName('div')).length == 0) {
			Element.hide($(this.infoID).parentNode.parentNode);
		}
		*/
		var indexj = null;
		for (var j=0; j < this.FILES_INFOS.length; j++) {
			if (this.FILES_INFOS[j].fid == ret.progressID) {
				indexj = j;
			}
		}
		if(typeof indexj == 'number') this.FILES_INFOS.splice(indexj, 1);
		
	}.bind(this);
	switch(ret.success) {
		case 1:
			/*
			var _img = $('photo_upload_info_' + ret.progressID).getElementsByTagName('img')[0];
			_img.src = this.uploadUrl +'?suname='+ ret.thumburl;
			_img.onload = function() {
				this.style.height = '60px';
				this.style.width = '80px';
				this.style.padding = '0px';
				this.style.margin = '0px';
				this.style.border = '0px';
			};
			$('photo_upload_info_' + ret.progressID).onclick = function() {
				changePostcardPhoto(this.uploadUrl + '?uname=' + ret.imgurl, ret, true, $('photo_upload_info_' + ret.progressID));
			}.bind(this);
			*/
			break;
		case -1:
			_dialog.alert({info: '图片上传出错，请重试！'});
			errImg(ret.progressID);
			break;
		case -2:
			_dialog.alert({info: '您上传的图片超出了大小，请限制在2M以内！'});
			errImg(ret.progressID);
			break;
		case -3:
			_dialog.alert({info: '图片存储失败，请重试！'});
			errImg(ret.progressID);
			break;
		case -4:
			_dialog.alert({info: '您上传了不支持的图片类型，请重试！'});
			errImg(ret.progressID);
			break;
		default:
			_dialog.alert({info: '未知错误，请重试！'});
			errImg(ret.progressID);
			break;
	}
};

function postcardUploadSuccess(ret) {
	mailUploadPhoto.endUpload(ret);
}
